<?php

use think\migration\Migrator;
use think\migration\db\Column;

class CreateVerificationCodesTable extends Migrator
{
    /**
     * 创建验证码表
     */
    public function up()
    {
        $table = $this->table('verification_codes', [
            'id' => false,
            'primary_key' => ['id'],
            'engine' => 'InnoDB',
            'collation' => 'utf8mb4_unicode_ci',
            'comment' => '邮箱验证码表'
        ]);
        
        $table->addColumn('id', 'integer', [
                'identity' => true,
                'signed' => false,
                'comment' => '验证码ID'
            ])
            ->addColumn('email', 'string', [
                'limit' => 255,
                'null' => false,
                'comment' => '邮箱地址'
            ])
            ->addColumn('code', 'string', [
                'limit' => 10,
                'null' => false,
                'comment' => '验证码'
            ])
            ->addColumn('type', 'string', [
                'limit' => 20,
                'null' => false,
                'default' => 'register',
                'comment' => '验证码类型：register-注册，reset-重置密码'
            ])
            ->addColumn('is_used', 'boolean', [
                'default' => false,
                'null' => false,
                'comment' => '是否已使用'
            ])
            ->addColumn('expired_at', 'datetime', [
                'null' => false,
                'comment' => '过期时间'
            ])
            ->addColumn('created_at', 'datetime', [
                'null' => false,
                'comment' => '创建时间'
            ])
            ->addColumn('updated_at', 'datetime', [
                'null' => false,
                'comment' => '更新时间'
            ])
            ->addIndex(['email'], ['name' => 'idx_verification_codes_email'])
            ->addIndex(['code'], ['name' => 'idx_verification_codes_code'])
            ->addIndex(['expired_at'], ['name' => 'idx_verification_codes_expired_at'])
            ->addIndex(['email', 'type', 'is_used'], ['name' => 'idx_verification_codes_email_type_used'])
            ->create();
    }

    /**
     * 删除验证码表
     */
    public function down()
    {
        $this->table('verification_codes')->drop()->save();
    }
}